package com.ang.juc.n5;

import com.ang.juc.nt.list.CopyOnWriteListTest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * CopyOnWriteArrayList是线程安全的，不需要加volatile，添加和不添加效果一样
 */
public class TestList {

    //使用ArrayList会报异常，ConcurrentModificationException
    private static CopyOnWriteArrayList<Integer> list1 = new CopyOnWriteArrayList<>();
    private static volatile CopyOnWriteArrayList<Integer> list2 = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        test1();
    }

    //不添加volatile的List
    public static void test1() throws InterruptedException {
        list1.add(1);

        Thread t1 = new Thread(() -> {
            while (true) {
                if (list1.get(0) == 10) {
                    break;
                }
            }
            System.out.println("终止");
        });
        t1.start();

        //睡眠1秒，等t1开始，给List添加元素
        Thread.sleep(1000);
        list1.set(0, 10);
    }
}
